﻿using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Ebt.Mvvm.Behaviors
{
    public class AppBarEx
    {
        public static readonly DependencyProperty IsOpenExProperty =
            DependencyProperty.RegisterAttached("IsOpenEx", typeof(bool), typeof(AppBarEx), new PropertyMetadata(DependencyProperty.UnsetValue, OnIsOpenExChanged));

        public static bool GetIsOpenEx(DependencyObject d)
        {
            return (bool)d.GetValue(IsOpenExProperty);
        }

        public static void SetIsOpenEx(DependencyObject d, bool value)
        {
            d.SetValue(IsOpenExProperty, value);
        }

        private static void OnIsOpenExChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
        {
            var appBar = (AppBar)d;

            appBar.Opened -= OnAppBarOpened;
            appBar.Closed -= OnAppBarClosed;

            appBar.Opened += OnAppBarOpened;
            appBar.Closed += OnAppBarClosed;

            appBar.IsOpen = (bool)args.NewValue;
        }

        private static void OnAppBarClosed(object sender, object e)
        {
            SetIsOpenEx((DependencyObject) sender, false);
        }

        private static void OnAppBarOpened(object sender, object o)
        {
            SetIsOpenEx((DependencyObject)sender, true);
        }
    }
}
